package cn.onein.edu.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.onein.edu.biz.bean.User;
import cn.onein.edu.web.common.base.BaseController;
import cn.onein.edu.web.util.AjaxCallBackJsonUtil;
import cn.onein.edu.web.vo.AjaxCallbackVO;

/**
 * Servlet Filter implementation class ServiceSecurityFilter
 */
public class ServiceSecurityFilter implements Filter {

    /**
     * Default constructor. 
     */
    public ServiceSecurityFilter() {
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
		boolean successedLogin = false;
		HttpServletRequest request = (HttpServletRequest)req;		

		HttpSession session = (HttpSession)request.getSession(false);
		if(session != null){
			User user = (User)session.getAttribute(BaseController.SESSION_USER_KEY);
			if(user != null){
				successedLogin = true;
			}
		}
		
		if(successedLogin == true){
			chain.doFilter(req, resp);
		}
		else{
			AjaxCallBackJsonUtil.callbackJSON(new AjaxCallbackVO(BaseController.AJAXTIMEOUT), (HttpServletResponse)resp);
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
	}

}
